import React, { Component, useState } from 'react';
import { Image, View } from '@tarojs/components';
import { AtButton, AtForm, AtImagePicker, AtInput, AtTextarea } from 'taro-ui'
// import Comments from '../../postBar/comments/comments';
import { AtMessage } from 'taro-ui'
// import { values } from 'lodash';
import Taro from '@tarojs/taro';
import moment from 'moment';
import NavBar from '../fit';
import './edit.scss';

const Edit = () => {
  const [Url, setUrl] = useState([]);
  const [article, setArticle] = useState('')
  const [title, steTitle] = useState('')

  const toBack = () => {
    Taro.navigateBack().then();
  }
  // 信息操作提醒
  const mesg = (type) => {
    Taro.atMessage({
      'message': type == "error" ? '请填写标题或内容再发表' : "发表成功",
      'type': type,
      duration: 2000,
    })
  }

  const handleChange = (res) => {
    console.log('输入了'+res);
    setArticle(res)
  }
  // 数据的保存
  const handleData = () => {
    if (article == undefined || title == undefined) {
      mesg("error")
      return
    }
    let data = [{
      userTitle: title,
      userContent: article,
      url: Url,
      author: Taro.getStorageSync("userInfo").nickName,
      author_url: Taro.getStorageSync("userInfo").avatarUrl,
      content_time: moment().format('YYYY-MM-DD:HH:MM:SS'),
      date: moment().format('YYYY-MM-DD')
    }]
    // 成功发表的信息提示
    mesg("success")
    // 调用云函数保存数据
    Taro.cloud.callFunction({
      name: "comments",
      data: {
        $url: "addForum",
        data
      }
    }).then(res => {
      console.log("成功插入数据:", res)
    })

    // 发表完数据后对发表栏进行清除
    setArticle('')
    steTitle('')
    setUrl([])
  }
  return (
    <View className="box">
      {/* {Comments} */}
      <View className="aa">
        <NavBar
          back={true}
        />
        <View className="box2">编辑</View>
      </View>
      <View className="box3">
        <AtInput
          name='title'
          type='text'
          placeholder='请输入标题'
          value={title}
          onChange={value => steTitle(value)}
        />
        <View className="article">
          <AtTextarea
            value={article}
            onChange={handleChange}
            maxLength={1000}
            height={350}
            placeholder='你的问题是...'
          />
        </View>

        <View className="img">
          <AtImagePicker
            mode="aspectFit"
            // multiple={true}
            length={3}
            count={6}
            files={Url}
            onChange={value => setUrl(value)}
          // onImageClick={}
          />
        </View>
        <View className="sub">
          <AtMessage />
          <AtButton type='primary' formType='submit' onClick={handleData}>发布</AtButton>
        </View>
      </View>
    </View>
  )
}


export default Edit;
